package de.openkanban.client.ui.adminpanel;

import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.user.client.ui.NamedFrame;
import com.smartgwt.client.types.Encoding;
import com.smartgwt.client.util.Page;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.FormItemIcon;
import com.smartgwt.client.widgets.form.fields.HeaderItem;
import com.smartgwt.client.widgets.form.fields.UploadItem;

import de.openkanban.client.login.LogIn;
import de.openkanban.client.ui.presenter.GetUserAccountRequestCallback;
import de.openkanban.client.ui.presenter.PreparedRequest;

/**
 * GUI Element for the UserAccountAvatarForm
 */
public class UserAccountAvatarForm extends DynamicForm {

	public static final String TARGET = "avatarUpdateTarget";

	private HeaderItem headerItem;

	private UploadItem avatarUrl;
	private FormItemIcon avatarIcon;
	private GetUserAccountRequestCallback getUserAccountRequestCallback;

	public UserAccountAvatarForm(int width) {
		getUserAccountRequestCallback = new GetUserAccountRequestCallback(this);

		headerItem = new HeaderItem();
		headerItem.setValue("change avatar");

		avatarIcon = new FormItemIcon();
		avatarIcon.setSrc(Page.getAppImgDir() + "avatar/" + LogIn.getUserDto().getAvatarUrl());

		avatarUrl = new UploadItem();
		avatarUrl.setName("avatar");
		avatarUrl.setTitle("Avatar 40x40 px");
		avatarUrl.setRequired(false);
		avatarUrl.setIcons(avatarIcon);

		// Hidden iFrame for uploading avatar image
		NamedFrame frame = new NamedFrame(TARGET);
		frame.setWidth("1px");
		frame.setHeight("1px");
		frame.setVisible(false);

		frame.addLoadHandler(new LoadHandler() {
			@Override
			public void onLoad(LoadEvent event) {
				PreparedRequest prepReq = new PreparedRequest("user", "account");
				prepReq.sendAsyncRequest(getUserAccountRequestCallback);
			}
		});

		setWidth(width);
		setMargin(10);
		setEncoding(Encoding.MULTIPART);
		setAction("service/user/update/avatar");
		setTarget(TARGET);

		// add components to form
		setFields(headerItem, avatarUrl);
		addChild(frame);
	}

	@Override
	public void submit() {
		submitForm();
	}

	public void updateAvatar() {
		avatarIcon.setSrc(Page.getAppImgDir() + "avatar/" + LogIn.getUserDto().getAvatarUrl());
		redraw();
	}
}
